// src/components/hiprint/index.ts （或你原来的文件名）

// ✅ 仅保留 CSS 引入（安全）
import "./css/hiprint.css";
import "./css/print-lock.css";

// ❌ 不再 import 任何 JS 文件！

// 声明全局类型
declare global {
	interface Window {
		autoConnect: boolean;
		hiwebSocket: HiWebSocket;
		hiprint: any;
	}
}

interface HiWebSocket {
	hasIo: () => boolean;
	start: (callback: ConnectionCallback) => void;
	stop: () => void;
}

type ConnectionCallback = (status: boolean, msg: any) => void;

// 从 window 获取 hiprint（确保 index.html 已加载）
const getHiprint = () => {
	if (typeof window.hiprint === "undefined") {
		throw new Error("hiprint is not loaded. Please include <script src='/libs/hiprint.bundle.js'> in index.html.");
	}
	return window.hiprint;
};

const hiprint = getHiprint();
const defaultElementTypeProvider = hiprint.defaultElementTypeProvider;

const autoConnect = (callback: ConnectionCallback): void => {
	console.log("Connecting to print service...");
	window.autoConnect = true;
	const socket = window.hiwebSocket;
	if (socket?.hasIo()) socket.start(callback);
};

const disAutoConnect = (): void => {
	console.log("Disconnecting from print service...");
	window.autoConnect = false;
	const socket = window.hiwebSocket;
	if (socket?.hasIo()) socket.stop();
};

const hiPrintPlugin = {
	disAutoConnect,
	install(Vue: any, name = "$hiPrint", enableAutoConnect = false): void {
		if (!enableAutoConnect) disAutoConnect();

		const globalVue = Vue.prototype || Vue.config.globalProperties;
		globalVue[name] = hiprint;

		globalVue.$print = (provider = defaultElementTypeProvider, template: string, ...args: any[]) => {
			hiprint.init({ providers: [provider()] });
			const hiprintTemplate = new hiprint.PrintTemplate({ template });
			hiprintTemplate.print(...args);
			return hiprintTemplate;
		};

		globalVue.$print2 = (provider = defaultElementTypeProvider, template: string, ...args: any[]) => {
			hiprint.init({ providers: [new provider()] });
			const hiprintTemplate = new hiprint.PrintTemplate({ template });
			hiprintTemplate.print2(...args);
			return hiprintTemplate;
		};
	},
};

// 可选：设置版本
hiprint.version = "1.0";
window.hiprint = hiprint;
window.autoConnect = false;

export { autoConnect, disAutoConnect, hiprint, hiPrintPlugin, defaultElementTypeProvider };
